﻿using System;
using System.Collections;
using UnityEngine;

public class HttpTool : MonoBehaviour
{


    private Sprite _localSprite;//我方的头像

    private Sprite _opponentSprite;//对方头像

    public Sprite LocalSprite
    {
        get { return _localSprite; }
    }

    public Sprite OpponentSprite
    {
        get { return _opponentSprite; }
    }

    public static HttpTool Instance
    {
        get { return _instance; }
    }

    private static HttpTool _instance = null;
   
    void Awake()
    {
        _instance = this;
    }

   
    /// <summary>
    /// 根据URL下载图片返回Sprite对象（开启协程），取Sprite从该单例中取得
    /// </summary>
    /// <param name="URL"></param>
    /// <returns></returns>
    public void GetImageConvertToSpriteByURL(string url, string type)
    {
        StartCoroutine(DownloadResource(url,type));
    }


    private IEnumerator DownloadResource(String url, string type)
    {
        WWW www = new WWW(url);//用WWW加载网络图片
        while (!www.isDone)
        {
            yield return new WaitForFixedUpdate();
        }
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            //获取Texture
            Texture2D texture = www.texture;
            //因为我们定义的是Image，所以这里需要把Texture2D转化为Sprite
            if (type.Equals("local"))
            {
                _localSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
                    new Vector2(0.5f, 0.5f));
            }else if (type.Equals("opponent"))
            {
                _opponentSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
                    new Vector2(0.5f, 0.5f));
            }
            else
            {
                Debug.LogError("错误的输入:"+type);
            }
            

        }
    }

    /// <summary>
    /// 清除已有的Sprite
    /// </summary>
    /// <param name="type"></param>
    public void ClearSprite(string type)
    {

        if (type.Equals("local"))
        {
            _localSprite = null;
        }else if (type.Equals("opponent"))
        {
            _opponentSprite = null;
        }else if (type.Equals("all"))
        {
            _localSprite = null;
            _opponentSprite = null;
        }else
        {
            Debug.LogError("错误的输入:"+type);
        }
    }
}